import { defineStore } from "pinia";
import { ref } from "vue";
import _ from "lodash";
export const useStore = defineStore('analysis', () => {
  const file = ref({
    xml: null as any,
    mid: null as any,
  })
  const xmlDataOri = {
    measures: [],
  }
  const xmlData = ref(_.cloneDeep(xmlDataOri));
  const setXmlData = (measures) => {
    xmlData.value.measures = measures;
  }
  const tone = ref({
    score_tone: null as string | null,
    chord_tone: "C",
  })
  const resultOri = {
    temp: "0",
    beat: "0",
    lyrics: [],
  }
  const result = ref(_.cloneDeep(resultOri));
  const setResult = (obj) => {
    result.value.temp = obj.temp;
    result.value.beat = obj.beat;
    result.value.lyrics = obj.lyrics;
  }
  // xml内容设置和弦
  const setChordXml = (e, measureIdx, noteIdx) => {
    xmlData.value.measures[measureIdx][noteIdx].choose = e.choose.name;
    xmlData.value.measures[measureIdx][noteIdx].chooseOri = e.chooseOri;
    xmlData.value.measures[measureIdx][noteIdx].chooseScore = e.chooseScore;
    xmlData.value.measures[measureIdx][noteIdx].chooseEnter = e.choose.enter;
    xmlData.value.measures[measureIdx][noteIdx].beat = e.beat;
  }
  // xml内容清除和弦
  const clearChordXml = (measureIdx, noteIdx) => {
    delete xmlData.value.measures[measureIdx][noteIdx].choose;
    delete xmlData.value.measures[measureIdx][noteIdx].chooseOri;
    delete xmlData.value.measures[measureIdx][noteIdx].chooseScore;
    delete xmlData.value.measures[measureIdx][noteIdx].chooseEnter;
    delete xmlData.value.measures[measureIdx][noteIdx].beat;
  }

  interface remarkInterface {
    name: string;
    text: string;
  }
  const remarks = ref([] as remarkInterface[]);
  const setRemark = (name: string, text: string) => {
    if(remarks.value.map(x => x.name).includes(name) || !name) {
      return;
    }
    remarks.value.push({
      name,
      text,
    });
  }
  const setRemarks = (arr: remarkInterface[]) => {
    remarks.value = arr;
  }
  const removeRemark = (name) => {
    const idx = remarks.value.findIndex(x => x.name === name);
    idx > -1 && remarks.value.splice(idx, 1);
  }
  const clearRemarks = () => {
    remarks.value = [];
  }
  const chordsData = ref([]);
  const setChordsData = (e) => {
    chordsData.value = e;
  }
  // 重置化
  const init = () => {
    file.value.mid = null;
    file.value.xml = null;
    xmlData.value = _.cloneDeep(xmlDataOri);
    tone.value.chord_tone = "C";
    tone.value.score_tone = null;
    result.value = _.cloneDeep(resultOri);
    clearRemarks();
    chordsData.value = [];
  }
  return {
    file,
    xmlData,
    tone,
    result,
    remarks,
    chordsData,
    setChordsData,
    setXmlData,
    setRemark,
    setRemarks,
    removeRemark,
    clearRemarks,
    setResult,
    setChordXml,
    clearChordXml,
    init,
  }
})